from flask import Flask, request, jsonify, render_template
from pydantic import BaseModel
from loguru import logger
import os
from dotenv import load_dotenv
from src.models.deepseek_finetune import DeepSeekFinetuner
from flask_cors import CORS

# 加载环境变量
load_dotenv()

app = Flask(__name__, 
    static_folder=os.path.join(os.path.dirname(__file__), "static"),
    template_folder=os.path.join(os.path.dirname(__file__), "templates"))

# 配置CORS
CORS(app, resources={r"/*": {"origins": "*"}})

class QuestionRequest(BaseModel):
    question: str
    department: str = "妇产科"

# 日志配置（保持原样）
logger.add(
    os.path.join(os.path.dirname(os.path.dirname(__file__)), 'app.log'),
    rotation="500 MB",
    retention="7 days",
    encoding="utf-8",
    level="DEBUG"
)

@app.route('/api/ask', methods=['POST'])
def ask_question():
    try:
        data = request.get_json()
        req = QuestionRequest(**data)

        if not req.question.strip():
            logger.warning("收到空问题")
            return jsonify({"error": "问题不能为空"}), 400

        logger.info(f"收到{req.department}问题：{req.question}")

        api_key = os.getenv('DEEPSEEK_API_KEY')
        logger.info(f"加载的API密钥长度: {len(api_key) if api_key else 0}")
        if not api_key or api_key == 'your_api_key_here' or len(api_key) < 32:
            logger.error("DeepSeek API密钥配置无效")
            return jsonify({"error": "系统配置错误：API密钥无效"}), 500

        try:
            # 初始化模型，启用知识库增强
            model = DeepSeekFinetuner(use_knowledge_base=True)
            logger.debug(f"模型初始化参数: {model.__dict__}")
        except Exception as e:
            logger.error(f"模型初始化失败：{str(e)}")
            return jsonify({"error": "模型服务初始化失败"}), 500

        prompt = f"你是一名专业的{req.department}医生，请用中文回答以下问题：\n{req.question}\n"

        try:
            logger.debug(f"API请求参数：{prompt[:200]}...")
            # 调用API时传入科室信息，用于知识库检索
            response = model.api_call(prompt, department=req.department)
            logger.info(f" Deeop seek response , API原始响应：{response}")

            if "choices" in response and len(response["choices"]) > 0:
                answer = response["choices"][0]["message"]["content"].strip()
                if not answer:
                    logger.error("API返回空答案")
                    return jsonify({"error": "模型未能生成有效答案，请重试"}), 500

                # 获取知识库检索的来源信息
                sources = response.get("sources", ["《医学知识库》"])
                logger.info(f"成功生成回答，长度：{len(answer)}，来源数量：{len(sources)}")
                
                return jsonify({
                    "answer": answer,
                    "sources": sources,
                    "status": "success",
                    "error_code": 0
                })

            logger.error("API响应格式异常")
            return jsonify({"error": "模型响应格式异常"}), 500

        except ValueError as e:
            error_msg = str(e)
            logger.error(f"API调用异常：{error_msg}")
            return jsonify({"error": error_msg}), 500

    except Exception as e:
        logger.error(f"请求处理异常：{str(e)}")
        return jsonify({"error": "服务器内部错误"}), 500

@app.route('/')
def index():
    return render_template('index.html')


@app.route('/pro2')
def indexpro2():
    return render_template('indexpro2.html')
 

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8000, debug=True)